using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading.Channels;

namespace RabbitMQ.DelayQueue
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //上述代码创建了-个名为delayed_queue的队列,，并将列绑定到名为delayed_exchange的交换机上， 
            //交换机为 x-delaved-mesage,通过 arguments 参教设置了x-delayed-type 为 direct，即使用 direct 类型的交换机路由消息
            var factory = new ConnectionFactory() { HostName = "", UserName = "admin", Password = "", Port = 5672, VirtualHost = "TestDelay" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    //创建延时队列
                    var arguments = new Dictionary<string, object>()
                    {
                        {"x-delayed-type","direct" }
                    };
                    channel.ExchangeDeclare("delayed_exchange", "x-delayed-message", arguments: arguments);
                    channel.QueueDeclare("delayed_queue", true, false, false, null);
                    channel.QueueBind("delayed_queue", "delayed_exchange", "delayed_routing_key", null);

                    //发送延时消息
                    var message = $"Hello, world!";
                    var body = Encoding.UTF8.GetBytes(message);
                    var properties = channel.CreateBasicProperties();

                    properties.Headers = new Dictionary<string, object> {
                        { "x-delay", 1000 },
                        { "retry_count", 0 }
                    };
                    properties.Headers["retry_count"] = (int)properties.Headers["retry_count"] + 1;
                    properties.Headers["x-delay"] = (int)properties.Headers["retry_count"] * 1000;

                    channel.BasicPublish("delayed_exchange", "delayed_routing_key", properties, body);

                    Console.WriteLine($"Send Success：{message},{DateTime.Now}");

                    Console.ReadKey();
                }

            }

        }
    }
}